package com.example.waibao.service.impl;

import com.example.waibao.entity.LoginUser;
import com.example.waibao.entity.ResponseResult;
import com.example.waibao.entity.ResponseResult2;
import com.example.waibao.entity.User;
import com.example.waibao.service.loginService;
import com.example.waibao.utils.Jwtutil;
import com.example.waibao.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class loginServiceImpl implements loginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {

        //AuthenticationManager 进行用户验证


        //测试：用户名上加上学校来达到查询学校的对应用户
        String username2 = user.getUser_name()+","+user.getSchool_id();
        //System.out.println(username2);

       // UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUser_name(), user.getPassword());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username2, user.getPassword());
        Authentication authenticate = authenticationManager.authenticate( authenticationToken);
        //如果验证失败，抛出异常，给出提示

        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //如果验证通过了，使用userid生成一个jwt，jwt存入ResponseResult中返回给前端

//        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
//        //判断是否是该学校的用户
//        if(loginUser.getUser().getSchool_id()!=user.getSchool_id()){
//            return new ResponseResult(401,"登录失败，用户名与学校不匹配");
//        }else {
//            String userId = loginUser.getUser().getId().toString();
//            String jwt = Jwtutil.createJWT(userId);
//
//            //把完整的用户信息存入redis userid作为key
//            redisCache.setCacheObject("login:"+userId,loginUser);
//
//            Map<String,String> map = new HashMap<>();
//            map.put("token",jwt);
//            loginUser.getUser().setPassword("");
//            map.put("user",loginUser.getUser().toString());
//            return new ResponseResult(200,"登录成功",map);
//        }

        //如果验证通过了，使用userid生成一个jwt，jwt存入ResponseResult中返回给前端
         LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String userId = loginUser.getUser().getId().toString();
        String jwt = Jwtutil.createJWT(userId);
        //把用户的学校id包装成token，python端要用
        String s = String.valueOf(loginUser.getUser().getSchool_id());
        String jwt2 = Jwtutil.createJWT(s);

        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:"+userId,loginUser);

        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        map.put("school_token",jwt2);
//        map.put("user",loginUser.getUser().toString());
        loginUser.getUser().setPassword("");
        map.put("id", String.valueOf(loginUser.getUser().getId()));

        map.put("user_name",loginUser.getUser().getUser_name());
        map.put("nick_name",loginUser.getUser().getNick_name());
        map.put("school_id", String.valueOf(loginUser.getUser().getSchool_id()));
        map.put("sex",loginUser.getUser().getSex());
        map.put("phoneNumber", String.valueOf(loginUser.getUser().getPhoneNumber()));
        map.put("user_type", String.valueOf(loginUser.getUser().getUser_type()));
        map.put("status", String.valueOf(loginUser.getUser().getStatus()));

        return new ResponseResult(200,"登录成功", map);
    }


    @Override
    public ResponseResult logout() {
        //获取SecurityContext中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"注销成功");
    }
}
